let cacheList = [];

const request = function (data) {
  fetch(`http://127.0.0.1:7001/monitor/web/report`, {
    method: 'POST', // or 'PUT'
    headers: new Headers({
      'Content-Type': 'application/json',
    }),
    body: JSON.stringify({
      list: data,
    }),
  });
};
function randomString(len) {
  len = len || 7;
  const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  const maxPos = $chars.length;
  let pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd + Date.now();
}
function markUser() {
  let markUser = sessionStorage.getItem('ps_markUser') || '';
  if (!markUser) {
    markUser = randomString();
    sessionStorage.setItem('ps_markUser', markUser);
  }
  return markUser;
}
let timer = null;
const report = function (data) {
  data = {
    user_id: 'Caroline',
    url_path: location.href,
    create_time: Date.now(),
    mark_user: markUser(),
    ...data,
  };
  // 存入缓存
  cacheList.push(data);
  if (timer) return;
  timer = setTimeout(() => {
    timer = null;
    request(cacheList);
    cacheList = [];
  }, 1000);
};

export default report;
